package com.xigua.xcar;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.ContentResolver;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.content.Intent;
import android.content.Intent.ShortcutIconResource;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Window;
import android.widget.RelativeLayout;

import com.xigua.xcar.constant.CommonUtil;

public class StartActivity extends Activity {
	private static final String tag = "StartActivity";
	private AlertDialog.Builder builder;
	private boolean isJump = false;
	private static final int CHECK_NET = 0;
	private static final int CHECK_SHORT = 1;
	private int mStatus = CHECK_NET;
	private Handler mHandler = new Handler(){

		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			switch(msg.what){
			case CHECK_NET:{
				mStatus = CHECK_SHORT;
				if(hasShortCut() || isFirstEntry()){
					mHandler.sendEmptyMessageDelayed(CHECK_SHORT, 1000);
				}else{
					StartActivity.this.showUpdateDlg("为生活创造捷径，您希望在桌面创建快捷方式吗？");
				}
				break;
			}
			case CHECK_SHORT:{
				if(!isJump){
					isJump = true;
					Intent intent = new Intent(StartActivity.this,MainTabActivity.class);
					StartActivity.this.startActivity(intent);
					StartActivity.this.finish();
				}
				break;
			}
			}
		}
		
	};
	
	private void createShortCut(){
		Log.i(tag, "createShortCut");
		Intent shortcut = new Intent("com.android.launcher.action.INSTALL_SHORTCUT");
		//快捷方式的名称
		shortcut.putExtra(Intent.EXTRA_SHORTCUT_NAME, getString(R.string.app_name));
		// shortcut.putExtra("duplicate", false); //不允许重复创建
		//指定当前的Activity为快捷方式启动的对象: 如 com.everest.video.VideoPlayer
		//注意: ComponentName的第二个参数必须加上点号(.)，否则快捷方式无法启动相应程序
		// ComponentName comp = new ComponentName(this.getPackageName(), "."+this.getLocalClassName());
		// shortcut.putExtra(Intent.EXTRA_SHORTCUT_INTENT, new Intent(Intent.ACTION_MAIN).setComponent(comp));
		shortcut.putExtra(Intent.EXTRA_SHORTCUT_INTENT, new Intent(this,StartActivity.class));
		//快捷方式的图标
		ShortcutIconResource iconRes = Intent.ShortcutIconResource.fromContext(this, R.drawable.icon); 
		shortcut.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, iconRes); 
		shortcut.putExtra("duplicate", false);
		sendBroadcast(shortcut); 
//		Intent shortcutintent = new Intent(  
//                "com.android.launcher.action.INSTALL_SHORTCUT");  
//        // 不允许重复创建  
//        shortcutintent.putExtra("duplicate", false);  
//        // 需要现实的名称  
//        shortcutintent.putExtra(Intent.EXTRA_SHORTCUT_NAME,  
//                R.string.app_name);  
//        // 快捷图片  
//        Parcelable icon = Intent.ShortcutIconResource.fromContext(  
//                getApplicationContext(), R.drawable.ic_launcher);  
//        shortcutintent.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, icon);  
//        // 点击快捷图片，运行的程序主入口  
//        shortcutintent.putExtra(Intent.EXTRA_SHORTCUT_INTENT,  
//                new Intent(getApplicationContext(), getClass()));  
//        
//        Intent intent = new Intent(Intent.ACTION_MAIN);
//	    intent.setFlags(Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
//	    intent.addFlags(Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY);
//	    intent.addCategory(Intent.CATEGORY_LAUNCHER);
//	    intent.setClass(getApplicationContext(), StartActivity.class);
//	    shortcutintent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, intent);
//        // 发送广播  
//        sendBroadcast(shortcutintent);  
	}
	
//		private static final Uri CONTENT_URI = 
//			Uri.parse("content://com.android.launcher.settings/favorites?notify=true");

		private static final String[] PROJECTION = {
			"_id",
			"title",
			"iconResource"
		};

		private boolean hasShortCut() {
			final ContentResolver cr = getContentResolver(); 
            int sdkVersion = android.os.Build.VERSION.SDK_INT;
            String AUTHORITY = "com.android.launcher2.settings"; 
            if(sdkVersion<8){
            AUTHORITY = "com.android.launcher.settings"; 
            }else{
             AUTHORITY = "com.android.launcher2.settings"; 
            }
            
            Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/favorites?notify=true");  
            Cursor c = cr.query(CONTENT_URI, PROJECTION, "title=?",   
                    new String[] {getString(R.string.app_name)}, null); 
            if (c!= null && c.moveToFirst()) {   
                c.close();   
                return true;   
            }
            return false;
		}
	
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		RelativeLayout layout = new RelativeLayout(this);
		layout.setBackgroundResource(R.drawable.startpage);
		setContentView(layout);
	}
	private static final String FIRSTENTRY = "first_entry";
	private boolean isFirstEntry(){
		boolean ret = false;
		SharedPreferences sp = this.getPreferences(MODE_WORLD_READABLE);
		ret = sp.getBoolean(FIRSTENTRY, false);
		return ret;
	}
	
	private void setFirstEntryFlag(){
		SharedPreferences sp = this.getPreferences(MODE_WORLD_WRITEABLE);
		Editor edit = sp.edit();
		edit.putBoolean(FIRSTENTRY, true);
		edit.commit();
	}
	
	@Override
	protected void onResume() {
		super.onResume();
		switch(mStatus){
		case CHECK_NET:{
			if(!isJump){
				int netType = CommonUtil.getAPNType(this);
				if(CommonUtil.NONET == netType){
					showUpdateDlg("亲，您当前的网络不可用，请设置网络后继续！\n精彩内容即将呈现！");
				}else{
					mHandler.sendEmptyMessage(CHECK_NET);
				}
			}
			break;
		}
		case CHECK_SHORT:{
			break;
		}
		}
	}
	
	private void showUpdateDlg(String content){
		if(null != builder){
			return ;
		}
		builder = new AlertDialog.Builder(this);  
	    builder.setTitle("提示");  
	    builder.setMessage(content); 
	    if(CHECK_NET == mStatus){
	    	builder.setPositiveButton("设置",  
		            new DialogInterface.OnClickListener() {  
		                public void onClick(DialogInterface dialog, int whichButton) {  
	                		CommonUtil.launchSystemNetworkSetting(StartActivity.this);
	                		builder = null;
		                }  
		            });
	    	builder.setNegativeButton("取消",  
		            new DialogInterface.OnClickListener() {  
		                public void onClick(DialogInterface dialog, int whichButton) {
		                	builder = null;
		                	CommonUtil.getAPNType(StartActivity.this);
		            		mHandler.sendEmptyMessageDelayed(CHECK_NET, 500);
		                }  
		            }).create();
	    }else{
	    	setFirstEntryFlag();
	    	builder.setPositiveButton("创建",  
		            new DialogInterface.OnClickListener() {  
		                public void onClick(DialogInterface dialog, int whichButton) {  
	                		createShortCut();
	                		builder = null;
	                		mHandler.sendEmptyMessageDelayed(CHECK_SHORT, 500);
		                }  
		            });
	    	builder.setNegativeButton("取消",  
		            new DialogInterface.OnClickListener() {  
		                public void onClick(DialogInterface dialog, int whichButton) {
		                	builder = null;
		                	CommonUtil.getAPNType(StartActivity.this);
		            		mHandler.sendEmptyMessageDelayed(CHECK_SHORT, 500);
		                }  
		            }).create();
	    } 
	    builder.setOnCancelListener(new OnCancelListener() {
			
			@Override
			public void onCancel(DialogInterface dialog) {
				Log.i(tag, "onCancel");
				builder = null;
				if(CHECK_SHORT == mStatus){
					mHandler.sendEmptyMessageDelayed(CHECK_SHORT, 500);
				}
			}
		});
	    builder.show();
	}

	@Override
	protected void onPause() {
		super.onPause();
	}

}
